package com.atguigu.ucenterservice.controller;

import com.atguigu.common.utils.JwtUtils;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import com.atguigu.ucenterservice.utils.ConstantPropertiesUtil;
import com.atguigu.ucenterservice.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller  //不需要返回数据，重定向到地址
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    //生成微信扫描二维码
    @GetMapping("login")
    public String genQrConnect() {
//        String url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + ConstantPropertiesUtil.WX_OPEN_APP_ID+
//                "&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE";
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //获取扫描之后调用域名地址，进行url编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //把值设置到%s位置
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
             );
        //重定向拼接好地址
        return "redirect:"+url;
    }

    @GetMapping("callback")
    public String callback(String code,String state) {

        //1 获取code值
        //2 拿着code请求微信固定的地址，得到openid和access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //设置参数
        baseAccessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code
            );
        //使用httpclient请求拼接好地址
        try {
            String result = HttpClientUtils.get(baseAccessTokenUrl);
            //从result得到openid和access_token
            Gson gson = new Gson();
            HashMap resultMap = gson.fromJson(result, HashMap.class);
            String access_token = (String)resultMap.get("access_token");
            String openid = (String)resultMap.get("openid");

            //拿着openid和access_token再去请求微信固定的地址，得到扫描人信息
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            baseUserInfoUrl = String.format(
                    baseUserInfoUrl,
                    access_token,
                    openid
                );
            //发送请求
            String userInfoResult = HttpClientUtils.get(baseUserInfoUrl);
            //从userInfoResult需要数据获取出来
            HashMap userInfoMap = gson.fromJson(userInfoResult, HashMap.class);
            String nickname = (String)userInfoMap.get("nickname");
            String headimgurl = (String)userInfoMap.get("headimgurl");

            //把获取出来微信信息添加数据库中
            //判断表是否有相同openid值，如果没有添加数据库
            UcenterMember member = this.getOpenId(openid);
            if(member == null) {
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }

            //根据member信息使用jwt生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            //进行登录，跳转到首页面中
            //把生成token字符串通过地址栏进行传递，url方式
            return "redirect:http://localhost:3000?token="+token;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public UcenterMember getOpenId(String openid) {
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UcenterMember member = memberService.getOne(queryWrapper);
        return member;
    }
}
